package org.amse.Archiver.algorithm;
import java.io.*;
import java.util.*;

import org.amse.Archiver.algorithm.huffman.*;
public class PrintDecoderReader implements IDecoder{
	private static final int STAT_LEN = 256;
    private final Scanner myInput;
    private OutputStream myOut;
    private ITree myTree;
    private int[] myStatistic  = new int[getStatLen()];
	private int mySize;
	private String myName;
	private File in;
	StringBuffer sb = new StringBuffer();
	
    public PrintDecoderReader (File input) throws IOException {
	    myInput = new Scanner(input);
	    in = input;
	    sb.append(in.getPath());
    } 
	
    public void readTechInf () throws IOException {
    	myName = myInput.nextLine();
    	mySize = myInput.nextInt();
    	for (int i = 0; i < getStatLen(); i++) {
    		int ch = myInput.nextInt();
    		myStatistic[i] = ch;
    	}
    }
    
    public void decode () throws IOException {
    	readTechInf();
    	sb.delete(sb.indexOf(in.getName()), sb.length()).append(myName);
    	myOut = new FileOutputStream(new File(sb.toString()));
    	myTree = new HuffmanTree(myStatistic);
    	myTree.buildTree();
    	int ch;
    	Node root = myTree.getRoot();
    	Node currentNode = root;
    	while (myInput.hasNextInt() == true) {
    	    ch = myInput.nextInt();
    		if (mySize == 0) {
    	    	return;
    	    }
    		if (currentNode.getLeft() != null && currentNode.getRight() != null){
    		    if (ch == 1) {
    		    	currentNode = currentNode.getLeft();
    		    }
    		    if (ch == 0) {
    		    	currentNode = currentNode.getRight();
    		    }
    	    } 
    		if(currentNode.getLeft() == null && currentNode.getRight() == null){
    	    	int sym = currentNode.getCodeSym();
    	    	myOut.write((char)sym);
    	    	mySize--;
    	    	currentNode = root;
    	    }	
    	}
    	myOut.close();
    }
    public int[] getStat(){
		return myStatistic;
	}
	public int getStatLen() {
		return STAT_LEN;
	}
	public String getName() {
		return sb.toString();
	}
}
